# @Auther: cty
# @Date: 2019/10/31
# @Description: 插入数据记录
# @version: 1.0

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost", "cty", "123456", "TESTDB")

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
         LAST_NAME, AGE, SEX, INCOME)
         VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
# 或
# sql = "INSERT INTO EMPLOYEE(FIRST_NAME, \
#        LAST_NAME, AGE, SEX, INCOME) \
#        VALUES ('%s', '%s',  %s,  '%s',  %s)" % \
#        ('Mac', 'Mohan', 20, 'M', 2000)

try:
   # 执行sql语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 如果发生错误则回滚
   db.rollback()

# SQL 查询语句
sql = "SELECT * FROM EMPLOYEE"
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表
   results = cursor.fetchall()
   for row in results:
      print("update table :%s" %str(row))
except:
   print ("Error: unable to fetch data")

# 关闭数据库连接
db.close()



'''
# 结果：
EMPLOYEE table :('Mac', 'Mohan', 20, 'M', 2000.0)
'''